package com.cylise.coolweather;

import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.icu.text.SimpleDateFormat;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.cylise.coolweather.service.AutoUpdateService;
import com.cylise.coolweather.util.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.NonWritableChannelException;
import java.text.DateFormat;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class WeatherActivity extends AppCompatActivity {
    List<Weather> weathers;
    TextView updateTime;
    TextView style;
    TextView countryName;
    TextView tmpNow;
    TextView wind;
    TextView aqi;
    TextView pm10;
    TextView pm25;
    LinearLayout air;
    LinearLayout hourly;
    LinearLayout sevenDay;
    LinearLayout suggest;
    SwipeRefreshLayout swipeRefreshLayout ;
    ScrollView scrollView;
    ImageView imageView;

    private IntentFilter intentFilter;
    private BroadcastReceiver refreshWeather;

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(refreshWeather);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(refreshWeather,intentFilter);
        Log.d("sendbroad","注册广播");

        Intent intentService = new Intent(this, AutoUpdateService.class);
        startService(intentService);
        Log.d("sendbroad","startService");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);

        intentFilter=new IntentFilter();
        intentFilter.addAction("com.cylise.coolweather.refresh");
        refreshWeather = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("sendbroad","接收广播");
                SharedPreferences sharedPreferences = getSharedPreferences("weather",MODE_PRIVATE);
                String weathersString = sharedPreferences.getString("weathers","");
                weathers=getWeather(weathersString);
                showWeather(weathers);
                //Toast.makeText(WeatherActivity.this,"refresh",Toast.LENGTH_SHORT).show();
            }
        };

        /*与状态栏融为一体*/
        if (Build.VERSION.SDK_INT >= 21){
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        updateTime = (TextView) findViewById(R.id.updateTime);
        style = (TextView) findViewById(R.id.style);
        countryName= (TextView) findViewById(R.id.countryName);
        tmpNow = (TextView) findViewById(R.id.tmpNow);
        wind = (TextView) findViewById(R.id.wind);
        aqi = (TextView) findViewById(R.id.aqi);
        pm10 = (TextView) findViewById(R.id.pm10);
        pm25 = (TextView) findViewById(R.id.pm25);
        air = (LinearLayout) findViewById(R.id.air);
        hourly = (LinearLayout) findViewById(R.id.hourly);
        sevenDay = (LinearLayout) findViewById(R.id.sevenDay);
        suggest = (LinearLayout) findViewById(R.id.suggest);
        imageView = (ImageView) findViewById(R.id.backImage);

        final DrawerLayout drawerLayout= (DrawerLayout) findViewById(R.id.drawerLayout);
        Button button= (Button) findViewById(R.id.selectCity);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });



        scrollView = (ScrollView) findViewById(R.id.scrollView);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                String countryId=getIntent().getStringExtra("weatherId");
                //Toast.makeText(this,countryId,Toast.LENGTH_SHORT).show();
                if (!countryId.isEmpty()){
                    setCountryTmp(countryId);
                }

                swipeRefreshLayout.setRefreshing(false);
            }
        });

        SharedPreferences sharedPreferences = getSharedPreferences("weather",MODE_PRIVATE);
        String weathersString = sharedPreferences.getString("weathers","");
        weathers=getWeather(weathersString);
        /*if (weathersString!=null &&getWeather(weathersString).get(0).){
            //Toast.makeText(this,weathers,Toast.LENGTH_SHORT).show();
            showWeather(weathers);
            scrollView.setVisibility(View.VISIBLE);
            return;
        }*/

        String countryId=getIntent().getStringExtra("weatherId");
        //Toast.makeText(this,countryId,Toast.LENGTH_SHORT).show();
        if (!countryId.isEmpty()){
            if (weathers!=null && "ok".equals(weathers.get(0).status)){
                Log.d("weathers",weathersString);
                if (!countryId.equals(weathers.get(0).basic.basicId)){
                    Log.d("weathers","从网上查询");
                    //Toast.makeText(this,"从网上查询"+countryId+" and "+weathers.get(0).basic.basicId,Toast.LENGTH_SHORT).show();
                    setCountryTmp(countryId);
                } else if (countryId.equals(weathers.get(0).basic.basicId)){
                    Log.d("weathers","不从网上查询");
                    //Toast.makeText(this,"不从网上查询",Toast.LENGTH_SHORT).show();
                    showWeather(weathers);

                }
            } else {
                setCountryTmp(countryId);
            }
        }


        getBackGround();

        /*Toolbar toolbar= (Toolbar) findViewById(R.id.toolBar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });*/
    }


    private void setCountryTmp(String weatherId){
        scrollView.setVisibility(View.GONE);

        String url="https://free-api.heweather.com/v5/weather?key=856153fdbb8d4dcc995cebea8a493b7e&city=";
        HttpUtil.sendOKHttpRequest(url + weatherId, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                WeatherActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WeatherActivity.this,"加载失败",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String body = response.body().string();
                SharedPreferences.Editor editor = getSharedPreferences("weather",MODE_PRIVATE).edit();
                editor.putString("weathers",body);
                editor.apply();

                //Toast.makeText(WeatherActivity.this,"无法从缓存读取",Toast.LENGTH_SHORT).show();
                weathers=getWeather(body);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showWeather(weathers);
                    }
                });

                   // JSONObject jsonObject= new JSONObject(body);

            }
        });
        scrollView.setVisibility(View.VISIBLE);

    }

    private  void getBackGround(){
        SharedPreferences sharedPreferences = getSharedPreferences("weather",MODE_PRIVATE);
        final String bingPic = sharedPreferences.getString("bingPic",null);

        if (bingPic!=null){
            //Bitmap bitmap = returnBitMap(bingPic);
            Glide.with(WeatherActivity.this).load(bingPic).into(imageView);
            return;
        }

        String url="http://guolin.tech/api/bing_pic";

        HttpUtil.sendOKHttpRequest(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String body = response.body().string();
                SharedPreferences.Editor editor = getSharedPreferences("weather",MODE_PRIVATE).edit();
                editor.putString("bingPic",body);
                editor.apply();
                //final Bitmap bitmap = returnBitMap(body);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        /*imageView.setImageBitmap(bitmap);*/
                        Glide.with(WeatherActivity.this).load(body).into(imageView);
                    }
                });
            }
        });
    }

    private Bitmap returnBitMap(String url) {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static List<Weather> getWeather(String weatherString){
        List<Weather> weathers=null;
        if (weatherString!=null){
            try {
                JSONObject jsonObject = new JSONObject(weatherString);
                String w=jsonObject.getString("HeWeather5");
                Gson gson=new Gson();
                weathers = gson.fromJson(w,new TypeToken<List<Weather>>(){}.getType());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        return weathers;
        /*runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //Toast.makeText(WeatherActivity.this,weathers.get(0).now.tmp,Toast.LENGTH_SHORT).show();
                showWeather(weathers);

            }
        });*/
    }

    private void showWeather(List<Weather> weathers){
        if (weathers.get(0).basic.update != null){
            updateTime.setText(weathers.get(0).basic.update.loc);
        }
        style.setText(weathers.get(0).daily_forecast.get(0).cond.txt_d);
        countryName.setText(weathers.get(0).basic.city);
        tmpNow.setText(weathers.get(0).now.tmp+"℃");
        wind.setText("风力："+weathers.get(0).now.wind.sc);

        hourly.removeAllViews();
        hourly.setWeightSum(weathers.get(0).hourly_forecast.size()>4?4:weathers.get(0).hourly_forecast.size());
        //Toast.makeText(this,weathers.get(0).hourly_forecast.size()+"",Toast.LENGTH_SHORT).show();
        for (int i=0;i<(weathers.get(0).hourly_forecast.size()>4?4:weathers.get(0).hourly_forecast.size());i++){
            View view = getLayoutInflater().inflate(R.layout.hourly_forecast_item,hourly,false);
            TextView hours = (TextView) view.findViewById(R.id.hours);
            TextView hourStyle = (TextView) view.findViewById(R.id.hourStyle);
            TextView hourTmp = (TextView) view.findViewById(R.id.hourTmp);
            hours.setText(weathers.get(0).hourly_forecast.get(i).date.substring(11));
            hourStyle.setText(weathers.get(0).hourly_forecast.get(i).cond.txt);
            hourTmp.setText(weathers.get(0).hourly_forecast.get(i).tmp+"℃");
            hourly.addView(view);
        }

        sevenDay.removeAllViews();
        for (int i=0;i<weathers.get(0).daily_forecast.size();i++){
            View view = getLayoutInflater().inflate(R.layout.dailyforecast_item,sevenDay,false);
            TextView day= (TextView) view.findViewById(R.id.day);
            TextView dayStyle = (TextView) view.findViewById(R.id.dayStyle);
            TextView tmpMax = (TextView)  view.findViewById(R.id.tmpMax);
            TextView tmpMin = (TextView)  view.findViewById(R.id.tmpMin);
            day.setText(weathers.get(0).daily_forecast.get(i).date);
            dayStyle.setText(weathers.get(0).daily_forecast.get(i).cond.txt_d);
            tmpMax.setText(weathers.get(0).daily_forecast.get(i).tmp.max);
            tmpMin.setText(weathers.get(0).daily_forecast.get(i).tmp.min);
            sevenDay.addView(view);
        }
        if (weathers.get(0).aqi!=null){
            air.setVisibility(View.VISIBLE);
            aqi.setText(""+weathers.get(0).aqi.city.aqi);
            pm25.setText(""+weathers.get(0).aqi.city.pm25);
            pm10.setText(""+weathers.get(0).aqi.city.pm10);
        } else {
            air.setVisibility(View.GONE);
        }

        suggest.removeAllViews();
        View view= getLayoutInflater().inflate(R.layout.suggest_item ,suggest,true);
        TextView comf = (TextView) view.findViewById(R.id.comf);
        comf.setText("舒适度："+weathers.get(0).suggestion.comf.brf+"。"+weathers.get(0).suggestion.comf.txt);
        TextView cw = (TextView) view.findViewById(R.id.cw);
        cw.setText("洗车指数："+weathers.get(0).suggestion.cw.brf+"。"+weathers.get(0).suggestion.cw.txt);
        TextView drsg = (TextView) view.findViewById(R.id.drsg);
        drsg.setText("穿衣指数："+weathers.get(0).suggestion.drsg.brf+"。"+weathers.get(0).suggestion.drsg.txt);
        TextView flu = (TextView) view.findViewById(R.id.flu);
        flu.setText("感冒指数："+weathers.get(0).suggestion.flu.brf+"。"+weathers.get(0).suggestion.flu.txt);
        TextView sport = (TextView) view.findViewById(R.id.sport);
        sport.setText("运动指数："+weathers.get(0).suggestion.sport.brf+"。"+weathers.get(0).suggestion.sport.txt);
        TextView trav = (TextView) view.findViewById(R.id.trav);
        trav.setText("旅游指数："+weathers.get(0).suggestion.trav.brf+"。"+weathers.get(0).suggestion.trav.txt);
        TextView uv = (TextView) view.findViewById(R.id.uv);
        uv.setText("紫外线："+weathers.get(0).suggestion.uv.brf+"。"+weathers.get(0).suggestion.uv.txt);
    }

    public static void updateWidget(Context context){
        Log.d("widget","update");
        CharSequence widgetTmp="";
        CharSequence widgetCity="";
        SharedPreferences sharedPreferences = context.getSharedPreferences("weather",MODE_PRIVATE);
        String weathersString = sharedPreferences.getString("weathers","");
        List<Weather> weathers=WeatherActivity.getWeather(weathersString);

        if (weathers!=null){
            widgetCity = weathers.get(0).basic.city;
            widgetTmp=weathers.get(0).now.tmp;
        }

        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.weather_widget);
        views.setTextViewText(R.id.appwidget_city, widgetCity);
        views.setTextViewText(R.id.appwidget_tmp,widgetTmp+"℃");
        ComponentName thisWidget = new ComponentName(context, WeatherWidget.class);
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        appWidgetManager.updateAppWidget(thisWidget, views);

    }
}
